package com.learn.Lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 需求: 可以多个线程同时读取,只能有一个写入
 *
 * 读共享 写独占 读写互斥
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        //MyCache cache = new MyCache();
        //添加读写锁解决  一写多读的问题
        MyCacheLock cache = new MyCacheLock();
        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(()->{
                cache.put(temp+"",temp+"");
            },temp+"").start();
        }

        for (int i = 1; i <= 10; i++) {
            final int temp = i;
            new Thread(()->{
                cache.get(temp+"");
            },temp+"").start();
        }
    }
}

/**
 * 添加读写锁解决
 */
class MyCacheLock{
    public Map<String,Object> map = new HashMap();
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    public void put(String key,Object value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"写入..");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入OK");
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }
    }
    public void get(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取..");
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }
}

/**
 * 这种不满足多读单写
 */
class MyCache{

    public Map<String,Object> map = new HashMap();

    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入..");
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入OK");
    }

    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取..");
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读取OK");
    }
}